package com.skyline.imagine.web;

import java.io.File;

import org.springframework.util.Assert;

public class UploadTempFile {
	private static final String UID = new java.rmi.server.UID().toString().replace(':', '_').replace('-', '_');
	private static int counter = 0;

	private final File storeLocation;
	private final boolean needClean;

	public UploadTempFile(File storeLocation, boolean needClean) {
		Assert.notNull(storeLocation, "storeLocation can't be null");
		this.storeLocation = storeLocation;
		this.needClean = needClean;
	}

	public File getStoreLocation() {
		return storeLocation;
	}

	public boolean isNeedClean() {
		return needClean;
	}

	public void clean() {
		if (this.isNeedClean()) {
			if (this.getStoreLocation().exists()) {
				this.getStoreLocation().delete();
			}
		}
	}
	
	@Override
	protected void finalize() throws Throwable {
		if (this.isNeedClean()) {
			if (this.getStoreLocation().exists()) {
				this.getStoreLocation().delete();
			}
		}
	}

	public static File createStoreLocation(String uploadTempDir) {
		if (uploadTempDir == null) {
			uploadTempDir = System.getProperty("java.io.tmpdir");
		}
		String tempFileName = "upload_" + (UID + "_" + getUniqueId()) + ".tmp";
		return new File(uploadTempDir, tempFileName);
	}

	private static String getUniqueId() {
		final int limit = 100000000;
		int current;
		synchronized (SwfUploadAction.class) {
			current = counter++;
		}
		String id = Integer.toString(current);

		// If you manage to get more than 100 million of ids, you'll
		// start getting ids longer than 8 characters.
		if (current < limit) {
			id = ("00000000" + id).substring(id.length());
		}
		return id;
	}
}
